<?php
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Http_Client');
Zend_Loader::loadClass('Zend_Http_Client_Adapter_Socket');
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_AuthSub');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Calendar');
Zend_Loader::loadClass('Zend_Json');
Zend_Loader::loadClass('Zend_Gdata_App_CaptchaRequiredException');

session_start();

$client = $_SESSION['client'];
/*$json = new Zend_Json();
$type = $_POST['type'];
$eid = $_POST['eid'];
$sDate = $_POST['sDate'];
$eDate = $_POST['eDate'];
//Temporarily commented out until I figure out how
//to properly call events.php
//getAllEvents($client);
/*
   if($type == "create"){

   } else if($type == "update"){
   updateEvent ($client, $eid, $newTitle); 
}	else if($type == "delete"){
	deleteEvent($client, $eid);
}	else if ($type == "getall"){
	getAllEvents($client);
}
*/
function deleteEvent ($client, $eventId){
        $gdataCal = new Zend_Gdata_Calendar($client);
	if ($eventDel = getEvent($client, $eventId)){
  	  echo "Removing: " . $eventDel->title->text . "<br />\n";
	  try {
	    $eventDel->delete();
	  } catch (Zend_Gdata_App_Exception $e) {
	    var_dump($e);
	    return null;
	  }
	  return 1;
	} else {
	  echo "Couldnt remove: " . $eventDel->title->text . "<br />\n";
	  return 0;
	}
}

/*
date_parse:
Array
(
    [year] => 2006
    [month] => 12
    [day] => 12
    [hour] => 10
    [minute] => 0
    [second] => 0
    [fraction] => 0.5
    [warning_count] => 0
    [warnings] => Array()
    [error_count] => 0
    [errors] => Array()
    [is_localtime] => 
)
*/
function getAllEvents($client){
	$events = array();
  $gdataCal = new Zend_Gdata_Calendar($client);
	//need to get the cal feed otherwise we can only get the default calendar's events
	$calFeed = $gdataCal->getCalendarListFeed();
	//add the calendar events to an array
	foreach($calFeed as $calendar) {
		foreach($gdataCal->getCalendarEventFeed($calendar->link[0]->href) as $event){
			$event->calColor = $calendar->color->value;
			$start = date_parse($event->when[0]->startTime);
			$end = date_parse($event->when[0]->endTime);
			$event->startDate = $start['month']."/".$start['day']."/".$start['year'];
			$event->endDate = $end['month']."/".$end['day']."/".$end['year'];
			$event->startTime = $start['hour'].":".$start['minute'];
			$event->endTime = $end['hour'].":".$end['minute'];
			$event->name = $event->title->text;
			$event->desc = $event->content->text;
			$event->place = $event->where[0]->valueString;
			$event->eid = $event->id->text;
			$events[] = $event;
		}
	}	
	return $events;
}
					    
function updateEvent ($client, $eventId, $newTitle, 
		$newDesc, $newWhere, $newStartDate, 
		$newStartTime, $newEndDate, $newEndTime, 
		$tzOffset)
{		
    $gdataCal = new Zend_Gdata_Calendar($client);
    if ($eventOld = getEvent($client, $eventId)) {
		$eventOld->title = $gdataCal->newTitle($newTitle);
		$eventOld->where = array($gdataCal->newWhere($newWhere));
		$eventOld->content = $gdataCal->newContent("$newDesc");
		$when = $gdataCal->newWhen();
	  
		if ($newStartTime!='' && $newEndTime!=''){
			
			$split_date2=split("-",$newStartDate);
			if (strlen($split_date2[2])==1){
				$split_date2[2]="0".$split_date2[2];
			}
			if (strlen($split_date2[1])==1){
				$split_date2[1]="0".$split_date2[1];
			}
			$split_date3=split("-",$newEndDate);
                        if (strlen($split_date3[2])==1){
				$split_date3[2]="0".$split_date3[2];
			}
			if (strlen($split_date3[1])==1){
				$split_date3[1]="0".$split_date3[1];
			}
																				
			$newNewStartDate=$split_date2[0]."-".$split_date2[1]."-".$split_date2[2];
			
			$newNewEndDate=$split_date3[0]."-".$split_date3[1]."-".$split_date3[2];
			
			
			$when->startTime = "{$newNewStartDate}T{$newStartTime}:00.00{$tzOffset}:00";
			$when->endTime = "{$newNewEndDate}T{$newEndTime}:00.00{$tzOffset}:00";
			
		}else {
			if($newStateDate!==''){
				$when->startTime = $newStartDate;
			}
			if ($newEndDate!==''){
				$when->endTime = $newEndDate;
			}
		}
		$eventOld->when = array($when);	
		try {
			$eventOld->save();
		} catch (Zend_Gdata_App_Exception $e) {
			var_dump($e);
			return null;
		}
			return 1;
	} else {
		return 0;
	 }
}

function createEvent ($client, $title='[untitled event]',
    $desc='', $where = '',
    $startDate, $startTime = '',
    $endDate, $endTime = '', $tzOffset = '-07', $calendarURI)
{
  $gdataCal = new Zend_Gdata_Calendar($client);
  $newEvent = $gdataCal->newEventEntry();
  
  $newEvent->title = $gdataCal->newTitle($title);
  $newEvent->where = array($gdataCal->newWhere($where));
  $newEvent->content = $gdataCal->newContent("$desc");
  
  $when = $gdataCal->newWhen();

  //Handle all day events:
  //from experience all day events are done like so
  //still need to check
    
  if ($startTime!='' && $endTime!=''){
 	 $when->startTime = "{$startDate}T{$startTime}:00.00{$tzOffset}:00";
 	 $when->endTime = "{$endDate}T{$endTime}:00.00{$tzOffset}:00";
  }else {
	$when->startTime = $startDate;
	$when->endTime = $endDate;
  }
  
  $newEvent->when = array($when);

  // Upload the event to the calendar server
  // A copy of the event as it is recorded on the server is returned
  
  
  //Figure out which calendar to put it on
  //based on:
  //http://groups.google.org.in/group/google-calendar-help-dataapi
  //tree/browse_frm/month/2007-10/430f7e5b8489d980?hide_quotes=no
  //#msg_2a070c66b15f75c1
  
 if (!$calendarURI){
  	$createdEvent = $gdataCal->insertEvent($newEvent);
  }
  else {
	$createdEvent = $gdataCal->insertEvent($newEvent,$calendarURI);
  }

  return $createdEvent->id->text;
}

	function getEvent($client, $eventId) 
	{ 
	  $gdataCal = new Zend_Gdata_Calendar($client); 
	  $query = $gdataCal->newEventQuery(); 
	  $query->setUser('default'); 
	  $query->setVisibility('private'); 
	  $query->setProjection('full'); 
	  $query->setEvent($eventId); 
	  try { 
	    $eventEntry = $gdataCal->getCalendarEventEntry($query); 
	    return $eventEntry; 
	  } catch (Zend_Gdata_App_Exception $e) { 
	    var_dump($e); 
	    return null; 
	  } 
	}

//function gets events from ALL calendars 	
	function outputCalendarByDateRange($client, $startDate='2006-01-01', $endDate='2010-012-31'){
		$gdataCal = new Zend_Gdata_Calendar($client);
		$calFeed = $gdataCal->getCalendarListFeed();
		$events = array();
		// get the calendar user ( $cals[1] for the first calendar... )
	foreach($calFeed as $calendar){
			$id = $calendar->id->text;
			$user = str_replace(Zend_Gdata_Calendar::CALENDAR_FEED_URI.'/default/', "", $id); // kind of dirty way to get the info, but its working :)
		
			$query = $gdataCal->newEventQuery();	
			$query->setUser($user);
	 		$query->setVisibility('private');
			$query->setProjection('full');	      
			$query->setOrderby('starttime');
			$query->setSortOrder('ascending');
			$query->setStartMin($startDate);
			$query->setStartMax($endDate);
			$events_aray =  $gdataCal->getCalendarEventFeed($query);
			
			foreach($events_aray as $event){
				$event->calColor = $calendar->color->value;
				$start = date_parse($event->when[0]->startTime);
				$end = date_parse($event->when[0]->endTime);
				$event->startDate = $start['month']."/".$start['day']."/".$start['year'];
				$event->endDate = $end['month']."/".$end['day']."/".$end['year'];
				$event->startTime = $start['hour'].":".$start['minute'];
				$event->endTime = $end['hour'].":".$end['minute'];
				$event->name = $event->title->text;
				$event->desc = $event->content->text;
				$event->place = $event->where[0]->valueString;
				$event->eid = $event->id->text;
				$events[] = $event;
			}
		}
		return $events;
	}
?>
